/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;
import utilitarios.ConnectionHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import pojo.Aluno;

    
    
/**
 *
 * @author guh
 */
public class DaoAluno implements DAO<Aluno> {

    private Connection conn = null;
    private PreparedStatement pstm = null;
    private ResultSet rs = null;
    Aluno aluno;
    String sql;

    public DaoAluno() {
        conn = ConnectionHelper.getIntance().getConnection();
    }
    
    
    
    @Override
    public void commit(Aluno beans) throws SQLException {
        sql = "insert into aluno (al_nome,al_idade,al_cpf) values (?,?,?)";
        pstm = conn.prepareStatement(sql);
        
        pstm.setString(1, beans.getNome());
        pstm.setInt(2, beans.getIdade());
        pstm.setString(3, beans.getCpf());
        
        pstm.execute();
    }

    @Override
    public Aluno findByName(String name) throws SQLException {
        sql = "select al_nome, al_idade, al_id, al_cpf from aluno where al_nome LIKE ?"; 
        pstm = conn.prepareStatement(sql);
        
        pstm.setString(1, name);
        pstm.execute();
        rs = pstm.getGeneratedKeys();
        
        aluno.setId(rs.getLong("al_id"));
        aluno.setNome(rs.getString("al_nome"));
        aluno.setIdade(rs.getInt("al_idade"));
        aluno.setCpf(rs.getString("al_cpf"));
        
        return aluno;
    }

    @Override
    public void delete(int id){
        try {
            sql = "delete from aluno where al_id = ?";
            pstm = conn.prepareStatement(sql);
            
            pstm.setLong(1, id);
            pstm.execute();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao deletar Aluno!");
        }
        
        
    }
    @Override
    public void update(Aluno entidade) throws SQLException {    
        sql = "UPDATE aluno SET al_name = ?, al_idade = ?, al_cpf = ? WHERE al_id = ?";
        pstm = conn.prepareStatement(sql);
        
        pstm.setString(1, entidade.getNome());
        pstm.setInt(2, entidade.getIdade());
        pstm.setString(3, entidade.getCpf());
        pstm.setLong(4, entidade.getId());
        pstm.execute();
        
    }
    
}
